/*
 * MpfillView.java
 */
package mpfill;

import de.umass.lastfm.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
import org.blinkenlights.jid3.*;
import org.blinkenlights.jid3.v2.*;

/**
 * The application's main frame.
 */
public class MpfillView extends FrameView {

    private File path = new File("d:\\Music\\Synced\\");
    private ArrayList folders = new ArrayList();
    private ArrayList filesNames = new ArrayList();
    private ArrayListComboBoxModel foldersModel;
    private String lastFmApiKey = "3a11b543e2159f0619e630b86efc47c2";
    private int neededGenreTags = 4;
    private String[] columnNames = {
        "Filename",
        "Current Genres",
        "New Genres"
    };
    private DefaultTableModel tableModel = new DefaultTableModel(
            new String[][]{},
            columnNames);

    public MpfillView(SingleFrameApplication app) {
        super(app);

        this.folders.add(path.toString());
        this.fillFolders(this.path);
        Collection col = System.getProperties().values();
        foldersModel = new ArrayListComboBoxModel(folders);
        foldersModel.setSelectedItem(foldersModel.getElementAt(0));
        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });


    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = MpfillApp.getApplication().getMainFrame();
            aboutBox = new MpfillAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        MpfillApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        jComboBox1.setModel(this.foldersModel);
        jComboBox1.setName("jComboBox1"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(mpfill.MpfillApp.class).getContext().getResourceMap(MpfillView.class);
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(this.tableModel);
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jComboBox1, 0, 386, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addComponent(jButton1))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(mpfill.MpfillApp.class).getContext().getActionMap(MpfillView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 485, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 465, Short.MAX_VALUE)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup()
                .addContainerGap(325, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(statusMessageLabel)
                        .addComponent(statusAnimationLabel))
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    /**
     * "Get Info" button
     * @param evt
     */
    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
        String item = this.jComboBox1.getSelectedItem().toString();
        try {
            this.showMediaFiles(item + "\\");
        } catch (ID3Exception ex) {
            Logger.getLogger(MpfillView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(MpfillView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MpfillView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton2MouseClicked

    /**
     * Save button
     * @param evt
     */
    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        int rowCount = this.tableModel.getRowCount();
        String genre = null;
        String filename = null;
        for (int i = 0; i < rowCount; i++) {
            filename = this.tableModel.getValueAt(i, 0).toString();
            genre = this.tableModel.getValueAt(i, 2).toString();

            File oSourceFile = new File(filename);
            MediaFile oMediaFile = new MP3File(oSourceFile);
            ID3V2_3_0Tag oID3V2_3_0Tag = new ID3V2_3_0Tag();
            try {
                oID3V2_3_0Tag.setGenre(genre);
            } catch (ID3Exception ex) {
                Logger.getLogger(MpfillView.class.getName()).log(Level.SEVERE, null, ex);
            }
            oMediaFile.setID3Tag(oID3V2_3_0Tag);
            try {
                oMediaFile.sync();
            } catch (ID3Exception ex) {
                Logger.getLogger(MpfillView.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }//GEN-LAST:event_jButton1MouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    public javax.swing.JComboBox jComboBox1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    public javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;

    /**
     * Gets directory list
     * @param path
     */
    private void fillFolders(File path) {
        int indentLevel = -1;
        File files[];
        indentLevel++;
        files = path.listFiles();

        Arrays.sort(files);
        for (int i = 0, n = files.length; i < n; i++) {
            for (int indent = 0; indent < indentLevel; indent++) {
            }
            if (files[i].isDirectory()) {
                this.folders.add(files[i].toString());
            }
            if (files[i].isDirectory()) {
                fillFolders(files[i]);
            }
        }
        indentLevel--;
    }

    /**
     * Returns file list of given path
     * @param path
     * @return
     */
    private ArrayList getMediaFileNames(File path) {
        ArrayList filesNamesList = new ArrayList();
        File files[];
        files = path.listFiles();
        String filename = null;

        for (int i = 0, n = files.length; i < n; i++) {
            filename = files[i].toString();
            if (files[i].isFile() && filename.matches(".+mp3")) {
                filesNamesList.add(files[i].toString());
                //System.out.println(files[i].toString());
            }
        }

        return filesNamesList;
    }

    /**
     * Fills media files table
     * @param filePath
     * @throws ID3Exception
     * @throws MalformedURLException
     * @throws IOException
     */
    private void showMediaFiles(String filePath) throws ID3Exception,
            MalformedURLException, IOException {

        this.progressBar.setValue(0);
        this.progressBar.setVisible(true);
        this.progressBar.repaint();

        int i;
        ArrayList filesNamesList = new ArrayList(this.getMediaFileNames(new File(filePath)));
        List cellsData;
        int rowsCount = filesNamesList.size();
        String currentGenre = "", currentArtist = "", currentTitle = "", lastFmGenre = "";
        for (i = 0; i < rowsCount; i++) {
            File mediaFileInf = new File(filesNamesList.get(i).toString());
            MediaFile mediaFile = new MP3File(mediaFileInf);
            ID3Tag[] mediaFileTags = mediaFile.getTags();
            for (int k = 0; k < mediaFileTags.length; k++) {
                if (mediaFileTags[k] instanceof ID3V2_3_0Tag) {
                    ID3V2_3_0Tag oID3V2_3_0Tag = (ID3V2_3_0Tag) mediaFileTags[k];

                    currentGenre = oID3V2_3_0Tag.getGenre();
                    currentArtist = oID3V2_3_0Tag.getArtist();
                    currentTitle = oID3V2_3_0Tag.getTitle();

                }
            }

            lastFmGenre = this.getLastFmSongGenreString(
                    currentArtist,
                    currentTitle,
                    currentGenre);

            this.tableModel.insertRow(i, new Object[]{
                        filesNamesList.get(i),
                        currentGenre,
                        lastFmGenre
                    });
            this.progressBar.setValue((100 * i) / rowsCount);
            this.progressBar.repaint();
        }
        this.progressBar.setValue(100);
        this.progressBar.repaint(0);
    }

    /**
     * Creates new genre string
     * @param currentArtist
     * @param currentTitle
     * @param currentGenre
     * @return
     * @throws MalformedURLException
     * @throws IOException
     */
    private String getLastFmSongGenreString(
            String currentArtist,
            String currentTitle,
            String currentGenre)
            throws MalformedURLException, IOException {
        String genre;
        String lastFmGenre = null;

        if (!currentGenre.contains(",")) {
            genre = currentGenre + ",";

            ArrayList lastFmGenres = new ArrayList(
                    this.getLastFmSongGenres(currentArtist, currentTitle));
            int i, rowsCount = lastFmGenres.size();
            for (i = 0; i < rowsCount; i++) {
                lastFmGenre = lastFmGenres.get(i).toString();
                if (!lastFmGenre.equalsIgnoreCase(currentGenre)) {
                    genre = genre + lastFmGenres.get(i) + ",";
                }
            }

            //clean up genre string
            int genrelen = genre.length();
            if (genrelen > 0) {
                if (genre.substring(genrelen - 1).equals(",")) {
                    genre = genre.substring(0, genrelen - 1);
                }
            }
        } else {
            genre = currentGenre;
        }

        return genre;
    }

    /**
     * Return ArrayList with lastFm genres
     * @param currentArtist
     * @param currentTitle
     * @return ArrayList with lastFm genres
     * @throws MalformedURLException
     * @throws IOException
     */
    private ArrayList getLastFmSongGenres(String currentArtist, String currentTitle)
            throws MalformedURLException, IOException {

        ArrayList lastFmGenres = new ArrayList();
        String key = this.lastFmApiKey;
        String currentTag = null;
        String[] currentTagArray;

        Collection<Tag> tags = Track.getTopTags(currentArtist, currentTitle, key);
        int i = 0;
        for (Tag tag : tags) {
            currentTag = tag.getName();

            currentTagArray = currentTag.split("\\s");
            for (int k = 0; k < currentTagArray.length; k++) {
                currentTag = currentTagArray[k].substring(0, 1).toUpperCase()
                        + currentTagArray[k].substring(1).toLowerCase() + " ";
            }
            currentTag = currentTag.trim();
            lastFmGenres.add(currentTag);
            i++;
            if (i >= this.neededGenreTags) {
                break;
            }
        }

        return lastFmGenres;
    }
}
